<?php
/**
 * user.php
 *
 * Create on 2015-8-17
 * Create by TT
 */
namespace haibao\app\data;

class Account extends \haibao\app\data\BaseMysql
{

    public function __construct()
    {
        parent::__construct('\haibao\app\model\data\Article');
    }

    public function setMessageList($userId, $systemType = null)
    {
        $sql = 'select LastTime from UserMessageLog where UserId=%s';
        $result = $this->query($sql, array($userId));

        $lastTime = null;
        while ($result->fetch_assoc()) {
            $lastTime = $result->getData('LastTime');
        }

        $sql = 'select Id,PublishTime from StationMessage where Published = 1 and Status = 1';
        if ($lastTime) {
            $sql .= ' and PublishTime >"' . $lastTime->format('Y-m-d H:i:s') . '"';
        }
        if (in_array($systemType, array(\haibao\app\model\data\PhoneInfo::OS_TYPE_IOS, \haibao\app\model\data\PhoneInfo::OS_TYPE_ANDROID))) {
            $sql .= ' and (PushObject = 0 or PushObject =' . $systemType . ')';
        }
        $result = $this->query($sql);
        $insertStr = '';
        while ($result->fetch_assoc()) {
            $createTime = $result->getData('PublishTime');
            $insertStr .= ',(' . $userId . ',' . $result->getData('Id') . ',0,"' . $createTime->format('Y-m-d H:i:s') . '")';
        }
        if ($insertStr) {
            $this->query('insert into UserMessage (UserId, MessageId,Status,CreateTime) values ' . substr($insertStr, 1));
        }

        if ($lastTime) {
            $this->query('update UserMessageLog set LastTime="' . date('Y-m-d H:i:s', time()) . '" where UserId=' . $userId);
        } else {
            $this->query('insert into UserMessageLog (UserId,LastTime) values(' . $userId . ',"' . date('Y-m-d H:i:s', time()) . '")');
        }
    }

    public function setMessageIsRead($userId, $messageId)
    {
        $sql = 'select Status from UserMessage where UserId=%s and MessageId=%s';
        $result = $this->query($sql, array($userId, $messageId));

        $status = \haibao\app\model\data\UserMessage::STATUS_UNREAD;
        while ($result->fetch_assoc()) {
            $status = (int)$result->getData('Status');
        }

        if ($status == \haibao\app\model\data\UserMessage::STATUS_UNREAD) {
            $this->query('update UserMessage set Status=%s where UserId=%s and MessageId=%s', array(\haibao\app\model\data\UserMessage::STATUS_READ, $userId, $messageId));
            $this->query('update StationMessage set ReadCount=ReadCount+1 where Id=%s', array($messageId));
        }
    }

    /**
     * 得到app用户未读消息数
     *
     * 按UsermessageLog表的最后一次日期，去消息表StationMessage查询(用户系统)，是否有新的消息，如果有，插入到UserMessage表，状态是未读。
     * 按UsermessageLog表的最后一次日期去UserMessage表里查询，是否有记录，有则表示有多少条新消息
     */
    public function getUnreadMessageNum($userId, $systemType = null)
    {
        $sql = 'select LastTime from UserMessageLog where UserId=%s';
        $result = $this->query($sql, array($userId));

        $lastTime = null;
        while ($result->fetch_assoc()) {
            $lastTime = $result->getData('LastTime');
        }

        $sql = 'select count(Id) as Num from StationMessage where Published = 1 and Status = 1';
        if ($lastTime) {
            $sql .= ' and PublishTime >"' . $lastTime->format('Y-m-d H:i:s') . '"';
        }
        if (in_array($systemType, array(\haibao\app\model\data\PhoneInfo::OS_TYPE_IOS, \haibao\app\model\data\PhoneInfo::OS_TYPE_ANDROID))) {
            $sql .= ' and (PushObject = 0 or PushObject =' . $systemType . ')';
        }
        $result = $this->query($sql);

        $messageNum = 0;
        while ($result->fetch_assoc()) {
            $messageNum = $result->getData('Num');
        }
        if ($messageNum > 0) {
            $sql = 'select count(q2.Id) as Num FROM `StationMessage` q1 LEFT JOIN `UserMessage` q2 ON q1.`Id` = q2.`MessageId` where  q2.Status=0 and q2.UserId=%s AND q1.`Status` = 1';
            $result = $this->query($sql, array($userId));

            $noReadNum = 0;
            while ($result->fetch_assoc()) {
                $noReadNum = $result->getData('Num');
            }
            $messageNum = $noReadNum + $messageNum;
        } else if ($lastTime) {
            //$sql = 'select count(Id) as Num from UserMessage where Status=0 and UserId=%s and CreateTime >"'.$lastTime->format('Y-m-d H:i:s').'"';
            $sql = 'select count(q2.Id) as Num FROM `StationMessage` q1 LEFT JOIN `UserMessage` q2 ON q1.`Id` = q2.`MessageId` where  q2.Status=0 and q2.UserId=%s AND q1.`Status` = 1 and q2.CreateTime >"' . $lastTime->format('Y-m-d H:i:s') . '"';
            $result = $this->query($sql, array($userId));

            while ($result->fetch_assoc()) {
                $messageNum = $result->getData('Num');
            }
            if ($messageNum > 0) {
                //$sql = 'select count(Id) as Num from UserMessage where Status=0 and UserId=%s';
                $sql = 'select count(q2.Id) as Num FROM `StationMessage` q1 LEFT JOIN `UserMessage` q2 ON q1.`Id` = q2.`MessageId` where  q2.Status=0 and q2.UserId=%s AND q1.`Status` = 1';
                $result = $this->query($sql, array($userId));

                while ($result->fetch_assoc()) {
                    $messageNum = $result->getData('Num');
                }
            }
        }

        return $messageNum;
    }

    public function deleteMessage($userId, $msgArr)
    {
        $str = preg_replace('/(\d+)/', '%s', implode(',', $msgArr));
        $param = $msgArr;
        array_unshift($param, $userId);
        array_unshift($param, \haibao\app\model\data\UserMessage::STATUS_DELETE);
        $this->query('update UserMessage set Status=%s where UserId=%s and MessageId in (' . $str . ')', $param);
    }

    public function addUserMessageLog($userId)
    {
        $this->query('insert into UserMessageLog (UserId,LastTime) values(' . $userId . ',"' . date('Y-m-d H:i:s', time()) . '")');
    }

    public function getAdvertList($adIdArray)
    {
        $cache = new \haibao\app\cache\Special();
        $adArr = $cache->getAdvertList();
        if (!$adArr) {
            $this->setConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_NEW_BI_UTF8);

            $str = preg_replace('/(\d+)/', '%s', implode(',', $adIdArray));
            $sql = 'select a.bannerid,b.interface_banner_id,b.filename,b.bannertext,b.weight,b.zone_id,b.pv_detection,b.url,b.title,c.interface_campaign_id from `banner_acls` as a inner join `banners` as b on a.bannerid=b.bannerid inner join clients as c on b.clientid=c.clientid where a.`data`="' . date('Ymd') . '" and b.zone_id in (' . $str . ') and b.weight=1 and filename!="" order by b.bannerid';
            $result = $this->query($sql, $adIdArray);

            $adArr = array();
            while ($row = $result->fetch_assoc()) {
                array_push($adArr, $row);
            }
            $cache->setAdvertList($adArr, 600);
        }
        return $adArr;
    }

    public function getPreAdvertList($adIdArray)
    {
        $this->setConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_NEW_BI_UTF8);

        $str = preg_replace('/(\d+)/', '%s', implode(',', $adIdArray));
        $sql = 'select distinct(a.bannerid),b.interface_banner_id,b.filename,b.bannertext,b.weight,b.zone_id,b.pv_detection,b.url,b.title,c.interface_campaign_id from `banner_acls` as a inner join `banners` as b on a.bannerid=b.bannerid inner join clients as c on b.clientid=c.clientid where b.`datastr`="' . date('Y/m/d') . '" and b.zone_id in (' . $str . ') and b.weight=1 and filename!="" order by b.bannerid';
        $result = $this->query($sql, $adIdArray);

        $adArr = array();
        while ($row = $result->fetch_assoc()) {
            array_push($adArr, $row);
        }
        return $adArr;
    }
}